// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  traceUser: true,
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { targetOpenid, senderInfo } = event
  const { OPENID: currentOpenid } = cloud.getWXContext()

  try {
    // 1. 保存交换请求到数据库
    const requestResult = await db.collection('exchange_requests').add({
      data: {
        sender_openid: senderInfo.openid,
        target_openid: targetOpenid,
        sender_info: senderInfo,
        status: 'pending', // pending: 待处理, confirmed: 已确认, rejected: 已拒绝
        create_time: db.serverDate()
      }
    })

    // 2. 发送模板消息给目标用户
    const templateMessageResult = await cloud.openapi.templateMessage.send({
      touser: targetOpenid,
      page: `/pages/card/requestDetail?id=${requestResult._id}`,
      data: {
        keyword1: {
          value: senderInfo.name || '用户'
        },
        keyword2: {
          value: '有人想与您交换名片'
        },
        keyword3: {
          value: new Date().toLocaleString()
        }
      },
      templateId: '你的模板消息ID', // 需在微信公众平台配置
      formId: 'placeholder' // 实际使用时需要前端传递formId
    })

    return {
      code: 0,
      msg: '请求发送成功',
      requestId: requestResult._id
    }
  } catch (err) {
    console.error('发送请求失败', err)
    return {
      code: 1,
      msg: '发送请求失败',
      error: err.message
    }
  }
}
